<template>
  <div class="app-container">
    <div class="page-card">
      <div class="page-form">
        <el-input
          v-model="queryParams.questionName"
          placeholder="题型名称"
          clearable
          @input="handleSearch"
        />
        <el-select
          v-model="queryParams.subjectiveType"
          placeholder="主/客观题型"
          clearable
          @change="handleSearch"
        >
          <el-option
            v-for="dict in dict.type.subjective_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-select
          v-model="queryParams.subjectIds"
          placeholder="所属学科"
          clearable
          @change="handleSearch"
        >
          <el-option
            v-for="dict in xklb"
            :key="dict.value"
            :label="dict.subjectName"
            :value="dict.subjectId"
          />
        </el-select>
      </div>
      <el-table
        stripe
        border
        ref="tableList"
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <!-- <el-table-column
          type="selection"
          width="55"
          align="center"
          :reserve-selection="true"
        /> -->
        <el-table-column
          label="题型名称"
          align="center"
          prop="questionName"
          :show-overflow-tooltip="true"
          width="140"
        />
        <el-table-column
          label="主/客观题"
          align="center"
          :show-overflow-tooltip="true"
          width="140"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.subjective_type"
              :value="scope.row.subjectiveType"
            />
          </template>
        </el-table-column>
        <el-table-column label="学科" align="center">
          <template slot-scope="scope">
            <km-tag :option="scope.row.subjectName" separator=" "></km-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="试题规则"
          align="center"
          prop="questionRuleInfo"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope" v-if="scope.row.multipleRuleId">
            <dict-tag
              :options="dict.type.multiple_rule"
              :value="scope.row.multipleRuleId"
            />
            <span v-if="scope.row.multipleRuleId != '2'">
              {{ scope.row.multipleScoring }}分
            </span>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-link type="primary" @click="edit(scope.row)">编辑</el-link>
            <el-link type="danger" @click="del(scope.row.id)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-bottom">
      <div class="sel-box">
        <p>共 {{ total }} 项</p>
        <el-button type="primary" @click="edit(false)" v-hasRole="['admin']"
          >添加题型</el-button
        >
        <!-- <el-button type="danger" :disabled="multiple" @click="del(false)"
          >批量删除</el-button
        > -->
      </div>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog
      ref="editDialog"
      class="editKmVisible"
      title="创建/编辑题型规则"
      :visible.sync="editKmVisible"
      width="470px"
      :before-close="beforeClose"
    >
      <el-form
        class="txglEditForm"
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-position="left"
        label-width="160px"
      >
        <el-form-item label="题型名称" prop="questionName">
          <el-input
            v-model="editForm.questionName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="主/客观题" prop="subjectiveType">
          <el-select
            v-model="editForm.subjectiveType"
            @change="editForm.questionType = ''"
          >
            <el-option
              v-for="dict in dict.type.subjective_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属学科" prop="subjectIds">
          <el-select v-model="editForm.subjectIds" multiple>
            <el-option
              v-for="dict in xklb"
              :key="dict.value"
              :label="dict.subjectName"
              :value="dict.subjectId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目规则" prop="questionType">
          <el-select v-model="editForm.questionType">
            <el-option
              v-for="dict in questionTypeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <template v-if="editForm.subjectiveType == '2'">
          <el-row :gutter="15">
            <el-col :span="9">
              <el-form-item
                label="选项共"
                prop="optionCount"
                label-width="64px"
              >
                <el-input
                  style="width: 87px"
                  v-model.number="editForm.optionCount"
                  autocomplete="off"
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item
                label="正确答案共"
                prop="optionRightCount"
                label-width="94px"
              >
                <el-select
                  style="width: 95px"
                  v-model.number="editForm.optionRightCount"
                >
                  <el-option
                    v-for="i in editForm.optionCount"
                    :key="i"
                    :label="i"
                    :value="i"
                  />
                  <el-option label="不定项" :value="0" />
                </el-select> </el-form-item
            ></el-col>
          </el-row>
          <template v-if="editForm.questionType == 2">
            <p>给分规则</p>

            <el-radio
              v-for="dict in dict.type.multiple_rule"
              :key="dict.value"
              v-model="editForm.multipleRuleId"
              :label="dict.value"
            >
              {{ dict.label }}
              <template v-if="dict.raw.remark == '1'">
                <el-input
                  v-if="editForm.multipleRuleId == dict.value"
                  class="mini-input"
                  size="mini"
                  v-model="editForm.multipleScoring"
                ></el-input>
                <span v-else>-</span>
                分</template
              >
            </el-radio>
          </template>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">返 回</el-button>
        <el-button type="primary" @click="editSubmit" :loading="loading"
          >保 存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  questionlist,
  questionAdd,
  questionEdit,
  questionDel,
} from "@/api/jcgl/txgl";
import { subjectlistselect } from "@/api/common";
import { debounce } from "lodash";
export default {
  name: "Basic_txgl",
  dicts: [
    "subjective_type",
    "disciplines_type",
    "question_type",
    "multiple_rule",
  ],
  data() {
    return {
      firstLoad: true,
      loading: false,

      ids: [],

      pageNum: 1,
      pageSize: 15,
      total: 0,
      tableData: [],

      multiple: true,

      queryParams: {
        pageNum: 1,
        pageSize: 15,
        questionName: "",
        subjectiveType: "",
        subjectIds: "",
      },

      xklb: [],
      editKmVisible: false,
      editForm: {
        questionName: "",
        subjectiveType: "",
        subjectIds: [],
        questionType: "",
        optionCount: "",
        optionRightCount: "",
        multipleRuleId: "",
        multipleScoring: 5,
      },
      rules: {
        questionName: [
          { required: true, message: "题型名称不能为空", trigger: "blur" },
        ],
        subjectiveType: [
          { required: true, message: "主/客观题不能为空", trigger: "change" },
        ],
        subjectIds: [
          { required: true, message: "所属学科不能为空", trigger: "change" },
        ],
        questionType: [
          { required: true, message: "题目规则不能为空", trigger: "change" },
        ],
        optionCount: [
          { required: true, message: "选项总数不能为空", trigger: "blur" },
        ],
        optionRightCount: [
          { required: true, message: "正确答案数不能为空", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    "editForm.multipleScoring"(newVal, oldVal) {
      const regex = /^-?\d*\.?\d{0,2}$/;
      if (!regex.test(newVal)) {
        // 如果输入不合法，回退到上一次的合法值
        this.editForm.multipleScoring = oldVal;
      }
    },
  },
  created() {
    this.getList();
    subjectlistselect("-1").then((res) => {
      this.xklb = res.data;
    });
  },
  activated() {
    if (!this.firstLoad) {
      this.getList();
    }
    this.firstLoad = false;
  },
  computed: {
    questionTypeList: function () {
      return this.dict.type.question_type.filter((item) => {
        return (
          item.raw.remark == "subjective_type:" + this.editForm.subjectiveType
        );
      });
    },
  },
  methods: {
    getList() {
      this.loading = true;
      this.tableData = [];
      questionlist(this.queryParams)
        .then((response) => {
          this.tableData = response.rows;
          this.total = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },

    edit(row) {
      if (row) {
        this.editForm.id = row.id;
        this.editForm.questionName = row.questionName;
        this.editForm.subjectiveType = row.subjectiveType.toString();
        this.editForm.questionType = row.questionType.toString();
        this.editForm.optionCount = row.optionCount;
        this.editForm.optionRightCount = row.optionRightCount;
        this.editForm.multipleRuleId = row.multipleRuleId
          ? row.multipleRuleId.toString()
          : "";
        this.editForm.multipleScoring = row.multipleScoring || 5;
        if (row.subjectIds) {
          this.editForm.subjectIds = row.subjectIds.split(",").map((item) => {
            return Number(item);
          });
        }
      }
      this.editKmVisible = true;
    },

    beforeClose(done) {
      this.editForm = {
        questionName: "",
        subjectiveType: "",
        subjectIds: [],
        questionType: "",
        optionCount: "",
        optionRightCount: "",
        multipleRuleId: "",
        multipleScoring: 5,
      };
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
        done();
      });
    },
    handleClose() {
      this.beforeClose(() => {
        this.editKmVisible = false;
      });
    },

    editSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          if (this.editForm.questionType == 2) {
            if (!this.editForm.multipleRuleId) {
              this.$modal.alertError("请选择给分规则");
              return;
            }
            if (
              this.editForm.multipleRuleId != "2" &&
              !this.editForm.multipleScoring
            ) {
              this.$modal.alertError("请输入给分规则分数");
              return;
            }
            const regex = /^\d+(\.\d{1,2})?$/;
            if (
              this.editForm.multipleRuleId != "2" &&
              !regex.test(this.editForm.multipleScoring)
            ) {
              this.$modal.alertError("给分规则分数格式错误");
              return;
            }
          }

          this.loading = true;
          let req;
          if (this.editForm.id) {
            req = questionEdit;
          } else {
            req = questionAdd;
          }
          req({
            ...this.editForm,
            subjectIds: this.editForm.subjectIds.join(","),
            multipleScoring: this.editForm.multipleScoring
              ? Number(this.editForm.multipleScoring)
              : null,
          })
            .then((res) => {
              this.$modal.msgSuccess("操作成功");
              this.handleClose();
              this.getList();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },

    del(id) {
      this.$modal.confirm("请确认进行删除操作").then(() => {
        questionDel(id ? id : this.ids).then((res) => {
          this.$modal.msgSuccess("操作成功");
          this.$refs.tableList.clearSelection();
          this.ids = [];
          this.getList();
        });
      });
    },

    debouncedSearch: debounce(function () {
    this.queryParams.pageNum = 1;
      this.getList();
    }, 500),

    handleSearch() {
      this.debouncedSearch();
    },
  },
};
</script>

<style lang="scss" scoped>
.editKmVisible {
  .el-input,
  .el-select {
    width: 240px;
  }
  .el-radio {
    margin-bottom: 10px;
  }
  .mini-input {
    width: 32px;
    margin: 0 5px;
  }
}
</style>

<style>
.txglEditForm .mini-input .el-input__inner {
  padding: 0 5px;
  text-align: center;
}
</style>